import type {
  SXTMessage,
  XHSConnection,
  XHSLike,
  XHSMention,
} from "@common/models";
import { makeMsgUUID, getNoteDetail } from "@common/utils/xhs";
import { get, post } from "./fetch";
import type { BaseResult, QueryResult } from "@/inject/metas";

const loadTalkMessages = ({
  porchUserId,
  customerId,
  limit,
  refStoreId,
  authorization,
}: {
  authorization: string;
  porchUserId: string;
  customerId: string;
  refStoreId?: number;
  limit?: number;
}) => {
  return get("/api-sxt/edith/chatline/msg", {
    searchParams: {
      ...(refStoreId
        ? {
            ref_store_id: refStoreId.toString(),
          }
        : {}),
      ...(limit ? { limit: limit.toString() } : {}),
      customer_user_id: customerId,
      porch_user_id: porchUserId,
    },
    headers: {
      authorization,
    },
  });
};

const sendTalkMessage = (params: {
  content: string;
  type: SXTMessage["sixin_message"]["message_type"];
  senderPorchId: string;
  receiverId: string;
  authorization: string;
}) => {
  return post(`/api-sxt/edith/chatline/msg`, {
    searchParams: {
      porch_user_id: params.senderPorchId,
    },
    data: {
      content: params.content,
      message_type: params.type,
      sender_porch_id: params.senderPorchId,
      receiver_id: params.receiverId,
      uuid: makeMsgUUID(),
      headers: {
        authorization: params.authorization,
      },
    },
  });
};

function makeXHSLoad<R>(category: string) {
  return async (params: {
    cursor?: number;
    num: number;
    xs: string;
    xsCommon: string;
  }) => {
    const res = await get(
      `https://edith.xiaohongshu.com/api/sns/web/v1/you/${category}`,
      {
        searchParams: {
          num: params.num.toString(),
          cursor: params.cursor?.toString() ?? "",
        },
        headers: {
          "x-s": params.xs,
          "x-s-common": params.xsCommon,
        },
      },
    );
    return res.data as R;
  };
}

async function getXHSUnread(params: { xs: string; xsCommon: string }) {
  const res = await get(
    "https://edith.xiaohongshu.com/api/sns/web/unread_count",
    {
      headers: {
        "x-s": params.xs,
        "x-s-common": params.xsCommon,
      },
    },
  );
  return res.data as BaseResult<{
    unread_count: number;
    likes: number;
    connections: number;
    mentions: number;
  }>;
}

export default {
  sxt: {
    loadTalkMessages,
    sendTalkMessage,
  },
  xhs: {
    loadMentions:
      makeXHSLoad<QueryResult<{ message_list: XHSMention[] }>>("mentions"),
    loadLikes: makeXHSLoad<QueryResult<{ message_list: XHSLike[] }>>("likes"),
    loadConnections:
      makeXHSLoad<QueryResult<{ message_list: XHSConnection[] }>>(
        "connections",
      ),

    getNoteDetail,
    getXHSUnread,
  },
};
